package org.study.quartz.quartzmanager;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.lang.reflect.Method;

/***
 * 定时任务详情信息
 */
public class QuartzIntegrationJobDetail extends QuartzJobBean {

    private Logger logger = LoggerFactory.getLogger(QuartzIntegrationJobDetail.class);

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {

        String targetBeanName = context.getJobDetail().getJobDataMap().getString("targetBeanName");
        String targetMethod = context.getJobDetail().getJobDataMap().getString("targetMethod");
        String applicationContextJobDataKey = context.getJobDetail().getJobDataMap()
                .getString("applicationContextJobDataKey");
        if (applicationContextJobDataKey == null || "".equalsIgnoreCase(applicationContextJobDataKey)) {
            applicationContextJobDataKey = "applicationContext";
        }
        try {
            ApplicationContext ac = (ApplicationContext) (context.getScheduler().getContext()
                    .get(applicationContextJobDataKey));
            Object target = ac.getBean(targetBeanName);
            Method method = target.getClass().getMethod(targetMethod);
            method.invoke(target);
        } catch (Exception e) {
            logger.error("执行任务失败", e);
        }

    }
}
